package com.zb;

import com.zb.eneity.Server;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.util.StringUtils;

import java.math.BigInteger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TenantDynamicDataSource extends AbstractRoutingDataSource {

    private final Map<Object,Object> targetDataSources = new ConcurrentHashMap<>();


    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        this.targetDataSources.putAll(targetDataSources);
        super.setTargetDataSources(this.targetDataSources);
        super.afterPropertiesSet();
    }

    /**
     * 动态添加数据源
     */
    public void addDataSource(String key,Object dataSource) {

        if (!this.targetDataSources.containsKey(key)) {
            this.targetDataSources.put(key,dataSource);
            super.setTargetDataSources(this.targetDataSources);
        }
        afterPropertiesSet();
    }

    @Override
    protected Object determineCurrentLookupKey() {
        String key = TenantContextHolder.getDataSource();
        return StringUtils.hasText(key) ? key : null;
    }
}
